const canvas = document.getElementById('gameCanvas');
const prepare = document.getElementById('prepare');

const joinUser1 = document.getElementById("join-player1");
const joinUser2 = document.getElementById("join-player2");

const user1Name = document.getElementById('player1-name');
const user2Name = document.getElementById('player2-name');

const turn = document.getElementById('turn');
const score = document.getElementById('score');

const gameStartText = document.getElementById('gameStartText');

const spectator = document.getElementById("spectators");
const joinSpectator = document.getElementById("join-as-spectator");

const surrender = document.getElementById("surrender");

const ctx = canvas.getContext('2d');

let layerAlert;


let color;
// 获取屏幕宽度
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
const tempLength = Math.min(screenWidth / 2, screenHeight);
// 设置canvas宽度为屏幕宽度的一半
canvas.height = canvas.width = tempLength;
const BOARD_SIZE = 20;
const CELL_SIZE = canvas.width / BOARD_SIZE;
const OFFSET = CELL_SIZE / 2; // 棋子中心对准网格线交点
let board = Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null));
let isBlackTurn = true;


const roomInfo = {
    roomState: 0,// 房间的游戏状态
    user1: { //玩家1
        name: '', // name
        status: 0, // 准备状态
    },
    user2: { // 玩家2
        name: '', // 昵称
        status: 0,// 准备状态
    },
    black: '', // 黑棋玩家
    white: '', // 白棋玩家
    winInfo: {}, // 胜利信息
    spector: [], // 观战席列表
    turnTo: '', // 谁的回合
}

// 画棋盘
function drawBoard() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    for (let i = 0; i < BOARD_SIZE; i++) {
        ctx.moveTo(i * CELL_SIZE + OFFSET, OFFSET);
        ctx.lineTo(i * CELL_SIZE + OFFSET, canvas.height - OFFSET);
        ctx.moveTo(OFFSET, i * CELL_SIZE + OFFSET);
        ctx.lineTo(canvas.width - OFFSET, i * CELL_SIZE + OFFSET);
    }
    ctx.stroke();
    // 处理点击事件
    // canvas.addEventListener('click', canvasClick);
}


// 画棋子
function drawStone(x, y, color) {
    ctx.beginPath();
    ctx.arc(x * CELL_SIZE + OFFSET, y * CELL_SIZE + OFFSET, CELL_SIZE / 2 - 2, 0, Math.PI * 2);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.strokeStyle = 'black'; // 可选：为棋子添加边框
    ctx.stroke();
}

// 显示胜利信息
function showWinMessage(player) {
    const winMessageElement = document.getElementById('winMessage');
    winMessageElement.textContent = `${player}棋获得胜利！`;
    winMessageElement.style.display = 'block';
}


// 检查胜利条件
function checkWin(x, y) {
    const messageBody = buildMessageBody();
    messageBody.x = x;
    messageBody.y = y;
    messageBody.operator = currentUser;
    messageBody.type = "CHECK_WIN";
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
    // const directions = [
    //     {dx: 1, dy: 0},  // 横向
    //     {dx: 0, dy: 1},  // 纵向
    //     {dx: 1, dy: 1},  // 右下斜向
    //     {dx: 1, dy: -1}  // 左下斜向
    // ];
    //
    // const currentPiece = board[row][col];
    //
    // for (let {dx, dy} of directions) {
    //     let count = 1; // 包括当前位置的棋子
    //     // 检查当前方向及其反方向的连续棋子
    //     count += countPieces(board, row, col, dx, dy, currentPiece);
    //     count += countPieces(board, row, col, -dx, -dy, currentPiece);
    //     if (count >= 5) {
    //         return true; // 找到了五个连续的棋子
    //     }
    // }
    // return false; // 没有找到五个连续的棋子
}

// 计算指定方向上连续棋子的数量
// function countPieces(board, row, col, dx, dy, piece) {
//     let count = 0;
//     let currentRow = row + dx;
//     let currentCol = col + dy;
//     // 沿着指定方向检查连续的棋子
//     while (isValidCell(board, currentRow, currentCol) && board[currentRow][currentCol] === piece) {
//         count++;
//         currentRow += dx;
//         currentCol += dy;
//     }
//     return count;
// }

// 检查坐标是否在棋盘范围内
function isValidCell(board, row, col) {
    return row >= 0 && row < board.length && col >= 0 && col < board.length;
}

// 显示胜利提示的layer
function showWinLayer(player) {
    // const winLayer = document.getElementById('winLayer');
    // const winMessage = document.getElementById('winMessage');
    // winMessage.textContent = `${player}棋获得胜利！`;
    // winLayer.style.display = 'block';
    let btn = "";
    let btnFunction = () => {};
    if(roomInfo.white === currentUser || roomInfo.black === currentUser) {
        btn = "重置游戏";
        btnFunction = function() {
            const messageBody = buildMessageBody();
            messageBody.operator = currentUser;
            messageBody.type = "RESET";
            buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
        };
    }
    // noinspection JSVoidFunctionReturnValueUsed
    layerAlert = layer.alert(`${player}棋获得胜利！`, {
        btn: [btn],
        btnAlign: 't',
        btn1:btnFunction,
    });
}


// 重置游戏
function resetGame(roomInfo) {
    // ...（重置棋盘和游戏状态的代码）
    board = Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null));
    drawBoard();
    canvas.removeEventListener('click', canvasClick);
    // const winLayer = document.getElementById('winLayer');
    // winLayer.style.display = 'none'; // 隐藏胜利提示的layer
    // 其他需要重置的状态...
    if(layerAlert){
        layer.close(layerAlert);
    }
    updateRoomInfo(roomInfo);
}

function clickResetGame() {
    const messageBody = buildMessageBody();
    messageBody.type = "RESET";
    messageBody.operator = currentUser;
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

// 给重置按钮添加点击事件监听器
// const resetButton = document.getElementById('resetButton');
// resetButton.addEventListener('click', clickResetGame);
surrender.addEventListener('click', clickResetGame);// 认输也是重置游戏
prepare.addEventListener('click', clickReady);


function buildWinInfo(key, user1, user2) {
    const returnValue = {};
    returnValue[key] = {
        user1: user1,
        user2: user2,
        user1Score: 0,
        user2Score: 0,
    }
    return returnValue;
}

function buildMessageBody() {
    return {
        x: 0,
        y: 0,
        type: '',
        operator: '',
        value: {},
        otherMessage: '',
    };
}

function updateRoomInfo(value) {
    roomInfo.user1 = value.user1;
    roomInfo.user2 = value.user2;
    roomInfo.white = value.white;
    roomInfo.black = value.black;
    roomInfo.roomState = value.roomState;
    roomInfo.spector = value.spector;
    roomInfo.winInfo = value.winInfo;
    roomInfo.turnTo = value.turnTo;
    console.log("刷新房间信息");
    console.log(roomInfo);
    user1Name.innerText = roomInfo.user1.name ? roomInfo.user1.name : "等待加入";
    user2Name.innerText = roomInfo.user2.name ? roomInfo.user2.name : "等待加入";
    joinUser1.style.display = roomInfo.user1.name ? "none" : "inline-block";
    joinUser2.style.display = roomInfo.user2.name ? "none" : "inline-block";
    const user1Ready = document.getElementById('user1Ready');
    const user2Ready = document.getElementById('user2Ready');
    if (roomInfo.user1.status && roomInfo.user2.status) {
        user1Ready.innerText = "";
        user2Ready.innerText = "";
    } else {
        user1Ready.innerText = roomInfo.user1.status ? "已准备" : "未准备";
        user2Ready.innerText = roomInfo.user2.status ? "已准备" : "未准备";
    }
    spectator.innerHTML = "";
    for (let i = 0; i < roomInfo.spector.length; i++) {
        spectator.innerHTML += "<br>" + roomInfo.spector[i];
    }
    gameStartText.innerHTML = "";
    if (roomInfo.roomState === 1) {
        gameStartText.innerHTML = "游戏开始";
    } else if (roomInfo.roomState === 2) {
        if (currentUser === roomInfo.turnTo) {
            gameStartText.innerHTML = '胜利';
        } else if (currentUser === roomInfo.user1.name || currentUser === roomInfo.user2.name) {
            gameStartText.innerHTML = '失败';
        } else {
            if (roomInfo.turnTo === roomInfo.black) {
                turn.innerText = '黑棋胜利';
            } else if (roomInfo.turnTo === roomInfo.white) {
                turn.innerText = '白棋胜利';
            }
        }
    }
}

joinUser1.addEventListener('click', clickJoinUser1);// 加入玩家1
joinUser2.addEventListener('click', clickJoinUser2);// 加入玩家2

/**
 * 点击加入对战席1号位
 */
function clickJoinUser1() {
    const messageBody = buildMessageBody();
    messageBody.otherMessage = "1";
    messageBody.type = 'JOIN_USER';
    messageBody.operator = currentUser;
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

/**
 * 点击加入对战席2号位
 */
function clickJoinUser2() {
    const messageBody = buildMessageBody();
    messageBody.otherMessage = "2";
    messageBody.type = 'JOIN_USER';
    messageBody.operator = currentUser;
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

/**
 * 加入观战席
 */
function clickJoinSpector() {
    if (roomInfo.spector.indexOf(currentUser) >= 0) {
        alert("已在观战席中");
        return;
    }
    const messageBody = buildMessageBody();
    messageBody.operator = currentUser;
    messageBody.type = 'JOIN_SPECTOR';
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

joinSpectator.addEventListener("click", clickJoinSpector);


function startGame(value) {
    updateRoomInfo(value);
    handleChangeTurn(value);
}

function clickReady() {
    const messageBody = buildMessageBody();
    messageBody.value = roomInfo;
    messageBody.type = 'READY';
    messageBody.operator = currentUser;
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

// function handleReady(messageBody){
//     updateRoomInfo(messageBody.value);
// }

function handleStartGame() {

}

/**
 * 点击画布落子
 * @param event
 */
function canvasClick(event) {
    canvas.removeEventListener('click', canvasClick);
    //点击后禁止canvas点击，轮到对方的回合
    const rect = canvas.getBoundingClientRect();
    const x = Math.floor((event.clientX - rect.left) / CELL_SIZE);
    const y = Math.floor((event.clientY - rect.top) / CELL_SIZE);
    if(board[x][y]){
        layer.msg('不能下在此处');
        canvas.addEventListener('click', canvasClick);
    }
    const messageBody = buildMessageBody();
    messageBody.x = x;
    messageBody.y = y;
    messageBody.type = 'LUOZI';
    messageBody.operator = currentUser;
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

function handleLuozi(message) {
    const x = message.x;
    const y = message.y;
    const roomInfo = message.value;
    if(roomInfo.roomState === 2) {
        return;
    }
    const operator = message.operator;
    let color = "";
    if (roomInfo.white === operator) {
        color = 'white';
    } else if (roomInfo.black === operator) {
        color = 'black';
    } else {
        console.error("错误的消息");
    }
    if (board[x][y]) return; // 如果格子已经有棋子，直接返回
    // const color = isBlackTurn ? 'black' : 'white';
    board[x][y] = color;
    drawStone(x, y, color);
    if (roomInfo.roomState === 1) {
        handleChangeTurn(roomInfo);
    }
}

function handleHuiqi() {
    const messageBody = buildMessageBody();
    messageBody.type = 'HUIQI';
    messageBody.operator = currentUser;
    buildWuZiQiWebsocketMessage(messageBody, new Date().getTime());
}

function handleWin(message) {
    canvas.removeEventListener('click', canvasClick);
    handleLuozi(message);
    updateRoomInfo(message.value);
    window.console.log("获胜")
    window.console.log(message.value.turnTo);
    let winner;
    if (message.value.turnTo === roomInfo.white) {
        winner = "白棋";
    } else if (message.value.turnTo === roomInfo.black) {
        winner = "黑棋";
    }
    showWinLayer(winner);
}

function handleChangeTurn(roomInfo) {
    if (roomInfo.roomState === 1) {
        if (currentUser === roomInfo.turnTo) {
            turn.innerText = '你的回合';
            canvas.addEventListener('click', canvasClick);
        } else if (currentUser === roomInfo.user1.name || currentUser === roomInfo.user2.name) {
            turn.innerText = '对方回合';
        } else {
            if (roomInfo.turnTo === roomInfo.black) {
                turn.innerText = '黑棋回合';
            } else if (roomInfo.turnTo === roomInfo.white) {
                turn.innerText = '白棋回合';
            }
        }
    } else {
        turn.innerText = '';
    }
}

// 初始化棋盘
drawBoard();
